import History from './History.js'

type ApplicationConstructorOptionsType = {
  history?: History
  landscapeMode?: boolean
}

export default class Application {
  history: History
  time: number
  requestId?: number
  screenWidth: number
  screenHeight: number
  landscapeMode?: boolean
  
  constructor(options: ApplicationConstructorOptionsType = {}) {
    this.history = options.history ?? new History()
    this.history.application = this
    this.landscapeMode = options.landscapeMode ?? false
    this.resize()
  }
  /**
   * 禁用缩放
   */
  stopGesture() {
    document.addEventListener('touchmove', function(event) {
      event.preventDefault();
    }, { passive: false });

    document.addEventListener('gesturestart', function(event) {
      event.preventDefault();
    }, { passive: false });
  }

  start() {
    this.time = Date.now()
    this.requestId = requestAnimationFrame(this.animate.bind(this))
    window.addEventListener('resize', this.resize.bind(this))
    this.resize()
    this.stopGesture()
  }

  destroy() {
    window.removeEventListener('resize', this.resize.bind(this))
    if(this.requestId) cancelAnimationFrame(this.requestId)
  }

  animate(dt: number) {
    if(this.history.transition) {
      this.history.transition.update(dt)
    }
    else if(this.history.currentScreen) {
      this.history.currentScreen.update(dt)
    }
    this.requestId = requestAnimationFrame(this.animate.bind(this))
  }

  resize() {
    if(this.landscapeMode) {
      this.screenWidth = Math.max(window.innerWidth, window.innerHeight) 
      this.screenHeight = Math.min(window.innerWidth, window.innerHeight) 
    } else {
      this.screenWidth = window.innerWidth
      this.screenHeight = window.innerHeight
    }
    if(this.history.currentScreen) {
      this.history.currentScreen.resize()
    }
  }
}